package com.yand.aop;


import com.yand.api.annotation.SysLogger;
import com.yand.api.entity.mq.syslog.SysLog;
import com.yand.api.entity.system.TSysUser;
import com.yand.rabbitmq.RabbitMQProducer;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;


/**
 * 日志切面类
 * 用于收集用户的操作日志,发送到rabbitmq 中
 */
@Aspect
@Component
public class LoggerAop {

    @Autowired
    private RabbitMQProducer rabbitMQProducer;

    @Pointcut("@annotation(com.yand.api.annotation.SysLogger)")
    public void loggerPointCut() {

    }


    /**
     * 保存日志, 将注解中的信息获取, 存储到rabbitmq 中
     * @param joinPoint
     */
    @Before("loggerPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        SysLog sysLog = new SysLog();
        SysLogger sysLogger = method.getAnnotation(SysLogger.class);
        if(sysLogger != null){
            TSysUser user = (TSysUser)SecurityUtils.getSubject().getPrincipal();
            //注解上的描述
            sysLog.setMessage(sysLogger.value());
            sysLog.setUserCode(user.getUserCode());
            rabbitMQProducer.sendObj(sysLog);
        }
        //请求的方法名
        /*String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        //sysLog.setMethod(className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params="";
        for(Object o:args){
          //  params+=JSON.toJSONString(o);
        }*/
       /* if(!StringUtils.isEmpty(params)) {
            sysLog.setParams(params);
        }
        //设置IP地址
        sysLog.setIp(HttpUtils.getIpAddress());
        //用户名
        String username = UserUtils.getCurrentPrinciple();
        if(!StringUtils.isEmpty(username)) {
            sysLog.setUsername(username);
        }
        sysLog.setCreateDate(new Date());
        //保存系统日志
        loggerService.log(sysLog);*/
    }
}
